import React, { useEffect, useState } from 'react';
import { addAllKml } from './utils/tool';

interface KmlState {
  type?: 'fc' | 'dl' | 'xl' | 'cable';
  name: string;
}

/**
 * 风场范围 切换显示隐藏
 */
const useKml = () => {
  const [kmlList, setKmlList] = useState<any[]>([]);

  /** kml - 风场 */
  const [fc, setFc] = useState<any[]>([]);

  /** 风场范围 - 显示/隐藏 */
  const [FcKmlVisible, setFcKmlVisible] = useState<boolean>(true);

  const [kmltrie, setKmltrie] = useState([]);

  /** kml - 道路 */
  const [dl, setDl] = useState<any[]>([]);

  /** kml - 线缆/电缆 */
  const [xl, setXl] = useState<any[]>([]);

  useEffect(() => {
    console.log({ FcKmlVisible, kmltrie });
    kmltrie.forEach((kml) => {
      if (kml && kml.KmlLayer && kml.KmlLayer.setVisible)
        kml.KmlLayer.setVisible(FcKmlVisible ? 1 : 0);
    });
  }, [FcKmlVisible]);

  useEffect(() => {
    const _fc: React.SetStateAction<any[]> = [];
    const _dl: React.SetStateAction<any[]> = [];
    const _xl: React.SetStateAction<any[]> = [];
    if (Array.isArray(kmlList))
      kmlList.forEach((kml) => {
        if (isFc(kml)) {
          _fc.push(kml);
        }
        if (isDl(kml)) {
          _dl.push(kml);
        }
        if (isXl(kml)) {
          _xl.push(kml);
        }
      });

    setFc(_fc);
    setDl(_dl);
    setXl(_xl);
  }, [kmlList]);

  useEffect(() => {
    // 先清空
    kmltrie.forEach((kml) => {
      if (kml && kml.KmlLayer && kml.KmlLayer.remove)
        kml.KmlLayer.remove();
    });

    console.log(fc);

    setKmltrie(
      addAllKml(
        fc,
        {
          opacity: FcKmlVisible ? 1 : 0,
        },
        {
          click: handleClickKML,
        },
      ),
    );
  }, [fc]);

  const isFc = (kml: KmlState) =>
    kml &&
    kml.type !== 'dl' &&
    kml.type !== 'cable' &&
    !kml.name.includes('道路') &&
    !kml.name.includes('电缆');
  const isDl = (kml: KmlState) => (kml && kml.type === 'dl') || kml.name.includes('道路');
  const isXl = (kml: KmlState) => (kml && kml.type === 'cable') || kml.name.includes('电缆');

  // 风场kml点击
  const handleClickKML = (entity) => {
    console.log(entity);
    if (entity && entity.styleOpt && entity.styleOpt.data) {
      console.log(entity.styleOpt.data);
    }
  };

  return { setKmlList, FcKmlVisible, setFcKmlVisible };
};

export default useKml;
